package online.flowerinsnow.minecraft.bukkit.testffa;

import online.flowerinsnow.minecraft.bukkit.testffa.command.SuicideCommand;
import online.flowerinsnow.minecraft.bukkit.testffa.core.TestFFACore;
import online.flowerinsnow.minecraft.bukkit.testffa.listener.MapProtectionListener;
import online.flowerinsnow.minecraft.bukkit.testffa.listener.PlayerProtectionListener;
import online.flowerinsnow.minecraft.bukkit.testffa.manager.*;
import online.flowerinsnow.minecraft.bukkit.testffa.runnable.CombatTimerRunnable;
import online.flowerinsnow.minecraft.bukkit.testffa.runnable.FakeGlassRunnable;
import org.bukkit.plugin.java.JavaPlugin;

public class Main extends JavaPlugin {
    private static Main instance;

    @Override
    public void onEnable() {
        instance = this;
        getLogger().info("加载配置文件...");
        saveDefaultConfig();
        reloadConfig();
        ConfigManager.config = getConfig();

        getLogger().info("初始化管理器...");
        TestFFACore.init(
                new CombatManagerImpl(),
                new EnderPearlCoolDownManagerImpl(),
                new StatsManagerImpl()
        );

        getLogger().info("连接数据库...");
        SQLManager.connect(ConfigManager.SQL_IP.getString(), ConfigManager.SQL_PORT.getInt(), ConfigManager.SQL_USER.getString(), ConfigManager.SQL_PASSWORD.getString());

        getLogger().info("注册监听器...");
        getServer().getPluginManager().registerEvents(new MapProtectionListener(), this);
        getServer().getPluginManager().registerEvents(new PlayerProtectionListener(), this);

        getLogger().info("注册线程...");
        getServer().getScheduler().runTaskTimer(this, new FakeGlassRunnable(), 0L, 5L);
        getServer().getScheduler().runTaskTimer(this, new CombatTimerRunnable(), 0L, 20L);

        SuicideCommand cmd = new SuicideCommand();
        getCommand("suicide").setExecutor(cmd);
        getCommand("suicide").setTabCompleter(cmd);
    }

    @Override
    public void onDisable() {
        getServer().getScheduler().cancelTasks(this);
        try {
            SQLManager.getConnection().close();
        } catch (Exception ignored) {
        }
    }

    public static Main getInstance() {
        return instance;
    }
}
